package com.easychat.websocket.netty;

import com.easychat.entity.config.AppConfig;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.timeout.IdleStateHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.PreDestroy;
import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * @program: easychat-java
 * @description: ws 启动类
 * @author: Mr.Wang
 * @create: 2024-12-07 12:14
 **/

@Component
public class NettyWebSocketStarter implements Runnable {

    private static final Logger logger = LoggerFactory.getLogger(NettyWebSocketStarter.class);

    @Resource
    private AppConfig appConfig;
    @Resource
    private HandlerWebSocket handlerWebSocket;
    /**
     * boss线程组用于处理连接工作
     */
    private static EventLoopGroup bossGroup = new NioEventLoopGroup(1);

    /**
     * worker线程组用于处理IO操作
     */
    private static EventLoopGroup workerGroup = new NioEventLoopGroup();

    /**
     * 资源关闭  在容器销毁时关闭
     */
    @PreDestroy
    public void close() {
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }

    @Override
    public void run() {
        try {
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(bossGroup, workerGroup);
            serverBootstrap.channel(NioServerSocketChannel.class)
                    .handler(new LoggingHandler(LogLevel.DEBUG))
                    .childHandler(new ChannelInitializer<Channel>() {
                        @Override
                        protected void initChannel(Channel channel) throws Exception {
                            ChannelPipeline pipeline = channel.pipeline();
                            //设置几个重要的处理器

                            //对http协议的支持,使用http的编码器,解码器
                            pipeline.addLast(new HttpServerCodec());
                            //对http请求进行聚合,最终得到一个FullHttpRequest或者FullHttpResponse
                            //保证收到的http请求的完整性
                            pipeline.addLast(new HttpObjectAggregator(64 * 1024));
                            /*
                             * readerIdleTime: 读超时. 即当在指定的时间间隔内没有从 Channel 读取到数据时, 会触发一个 READER_IDLE_TIMEOUT 事件
                             * writerIdleTime: 写超时. 即当在指定的时间间隔内没有数据写入到 Channel 时, 会触发一个 WRITER_IDLE_TIMEOUT 事件
                             * allIdleTime: 读/写超时. 即当在指定的时间间隔内没有读或写操作时, 会触发一个 ALL_IDLE_TIMEOUT 事件
                             * TimeUnit: 时间单位
                             */
                            pipeline.addLast(new IdleStateHandler(60, 0, 0, TimeUnit.SECONDS));
                            //超时事件 心跳处理
                            pipeline.addLast(new HandlerHearBeat());
                            //对websocket的支持,使用websocket的编码器,解码器
                            pipeline.addLast(new WebSocketServerProtocolHandler("/ws",null,
                                    true,64 * 1024,true,
                                    true,100000L));
                            //自定义处理器
                            pipeline.addLast(handlerWebSocket);

                        }
                    });
            //启动服务
            ChannelFuture channelFuture = serverBootstrap.bind(appConfig.getWsPort()).sync();
            logger.info("netty服务启动成功");
            channelFuture.channel().closeFuture().sync();
        } catch (Exception e) {
            logger.error("netty服务启动失败", e);
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }
}
